<template>
  <div class="register-view">
    <div class="container">
      <h1 class="title">注册新用户</h1>
      <el-form
        :model="form"
        label-width="auto"
        label-position="right"
        class="register-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="form.password2" show-password />
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button type="primary" @click="handleSubmit">注册新用户</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { userRegisterHttp } from "@/api/user";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();
const form = reactive({
  username: "",
  password: "",
  password2: "",
});

const handleSubmit = async () => {
  const { username, password } = form;
  // 验证输入
  if (!username || !password || !form.password2) {
    return ElMessage.error("用户名和密码不能为空");
  } else if (password !== form.password2) {
    return ElMessage.error("两次输入的密码不一致");
  }
  // 发送注册请求
  const res = await userRegisterHttp({ username, password });
  if (res.code === 200) {
    setTimeout(() => {
      router.push({ name: "login" });
    });
  }
};
</script>

<style scoped lang="scss">
.register-view {
  margin: 0 auto;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: #f0f4f9;
  padding: 20px;
  .container {
    border: 1px solid #e6e6e6;
    width: 600px;
    border-radius: 10px;
    background: #fff;
    position: absolute;
    top: 30%;
    left: 50%;
    .title {
      text-align: center;
    }
    .register-form {
      margin: 20px;
    }
    .btn {
      margin: 10px auto;
      display: flex;
      justify-content: center;
    }
  }
}
</style>
